<!---总览数据页面-->
<template>
  <div class="ele-body ele-body-card">
    <a-card title="相机监控" class="card-width">
      <!-- 添加牛的数量信息显示在图片上方 -->
      <div v-if="cowInfo.visible" class="cow-info-container">
        <div class="cow-info-item">识别到的牛: <span class="cow-count">{{ cowInfo.cowCount }}</span></div>
        <div class="cow-info-item">上枷的牛: <span class="cow-count">{{ cowInfo.eatCowCount }}</span></div>
      </div>
      
      <div class="camera-live-view">
        <div class="image-container">
          <img :src="currentImageUrl" alt="相机图片" class="camera-image" />
          <div class="live-button" :class="{ 'live-active': isLive }" @click="toggleLive">
            实况
          </div>
        </div>
      </div>
    </a-card>
  </div>
</template>

<script>
import {DeviceAiEdgeCameraRecogniseApi} from "@/api/property/aiedgecomputer/DeviceAiEdgeCameraRecogniseApi";

export default {
  name: 'DeviceManagerdeviceAiedgeComputerCameraMonitorvideo',
  components: {
  },
  props: {
    data: Object
  },
  data() {
    return {
      aiedgecomputer: {},
      currentImageUrl: this.data && this.data.coverUrl ? this.addNoCacheParam(this.data.coverUrl) : '',
      isLive: false,
      liveInterval: null,
      isRefreshing: false, // 添加刷新状态标记
      cowInfo: {
        visible: false,
        cowCount: 0,
        eatCowCount: 0
      }
    };
  },
  mounted() {
    // 如果有coverUrl，直接显示
    if (this.data && this.data.coverUrl) {
      this.currentImageUrl = this.addNoCacheParam(this.data.coverUrl);
    }
  },
  beforeUnmount() {
    // 组件销毁前停止实况
    this.stopLive();
  },
  methods: {
    getDetail() {
      let that = this;
      DeviceAiEdgeComputerApi.detailByRecord(this.data.recordId).then(result => {
        that.aiedgecomputer = result || {};
      });
    },
    
    // 添加防缓存参数
    addNoCacheParam(url) {
      if (!url) return '';
      const separator = url.includes('?') ? '&' : '?';
      return `${url}${separator}_t=${new Date().getTime()}`;
    },
    
    // 切换实况状态
    toggleLive() {
      this.isLive = !this.isLive;
      if (this.isLive) {
        this.startLive();
      } else {
        this.stopLive();
      }
    },
    
    // 开始实况
    startLive() {
      // 立即刷新并获取一次最新图片
      this.refreshAndFetchImage();
      
      // 设置定时器，每15秒刷新并获取一次最新图片
      this.liveInterval = setInterval(() => {
        this.refreshAndFetchImage();
      }, 15000); // 15秒
    },
    
    // 停止实况
    stopLive() {
      if (this.liveInterval) {
        clearInterval(this.liveInterval);
        this.liveInterval = null;
      }
      this.isRefreshing = false; // 重置刷新状态
    },
    
    // 刷新并获取最新图片
    async refreshAndFetchImage() {
      // 如果正在刷新中，则跳过
      if (this.isRefreshing) {
        return;
      }
      
      this.isRefreshing = true;
      
      try {
        console.log('请求刷新接口，cameraId:', this.data.cameraId);
        // 先请求刷新接口
        await DeviceAiEdgeCameraRecogniseApi.refresh(this.data.cameraId);
        
        console.log('刷新接口请求成功，等待5秒后获取最新图片');
        // 等待5秒后获取最新图片
        setTimeout(async () => {
          try {
            console.log('开始获取最新图片');
            const response = await DeviceAiEdgeCameraRecogniseApi.findLastOne(this.data.cameraId);
            console.log('获取最新图片响应:', response);
            
            let imgUrl = null;
            // 更新牛的数量信息
            if (response) {
              // 检查并更新牛的数量信息
              this.updateCowInfo(response);
              
              imgUrl = response.data.coverUrl;
            }
            
            if (imgUrl) {
              // 添加时间戳防止缓存
              this.currentImageUrl = this.addNoCacheParam(imgUrl);
              console.log('更新图片URL:', this.currentImageUrl);
            } else {
              console.warn('响应中没有找到有效的图片URL');
            }
          } catch (error) {
            console.error('获取最新图片失败:', error);
          } finally {
            this.isRefreshing = false; // 完成刷新
          }
        }, 5000); // 5秒后获取最新图片
      } catch (error) {
        console.error('请求刷新接口失败:', error);
        this.isRefreshing = false; // 出错时也要重置刷新状态
      }
    },
    
    // 更新牛的数量信息
    updateCowInfo(response) {
      let data = response;
      if (response.data) {
        data = response.data;
      }
      
      // 检查是否有牛的数量信息
      if (data.cowCount !== undefined || data.eatCowCount !== undefined) {
        this.cowInfo.visible = true;
        
        if (data.cowCount !== undefined) {
          this.cowInfo.cowCount = data.cowCount;
        }
        
        if (data.eatCowCount !== undefined) {
          this.cowInfo.eatCowCount = data.eatCowCount;
        }
        
        console.log('更新牛的数量信息:', this.cowInfo);
      }
    }
  }
};
</script>
<style scoped>
.block-space-top {
  /*上右下左*/
  padding: 10px 0 0 0;
}

.block-space-right {
  padding: 0 5px 0 0;
}

.block-space-left {
  padding: 0 0 0 5px;
}

.card-width {
  width: 100%;
}

.camera-live-view {
  position: relative;
  width: 100%;
  height: 100%;
}

.image-container {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 300px;
  overflow: hidden;
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.camera-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.live-button {
  position: absolute;
  bottom: 10px;
  right: 10px;
  padding: 5px 10px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #999;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
}

.live-active {
  background-color: rgba(0, 128, 0, 0.7);
  color: white;
}

/* 牛的数量信息样式 */
.cow-info-container {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.cow-info-item {
  margin-left: 20px;
  font-size: 14px;
}

.cow-count {
  font-weight: bold;
  color: #1890ff;
}

@media screen and (max-width: 880px) {
  .analysis-tabs-extra {
    display: none;
  }
}
</style>
